import type {
  FullTableProps,
  TableSetting,
  DataTableColumn,
  ColumnCache,
} from "./types";
import { localStg, debounce, cloneDeep } from "@/utils";

export const useCacheKey = (prefix: string = "basic:table") => {
  const cacheKey = {
    column: prefix + ":column",
    setting: prefix + ":setting",
    alive: prefix + ":alive",
  };
  return { cacheKey };
};

export const useCache = (props: FullTableProps) => {
  const { cacheKey } = useCacheKey(props.cacheKey);
  const columnsCache: ColumnCache[] = localStg.get(cacheKey.column);
  const settingCache: TableSetting = localStg.get(cacheKey.setting);
  const aliveCache: string[] = localStg.get(cacheKey.alive);

  const cloneColumns = cloneDeep(props.columns);
  const tableColumns = ref<DataTableColumn[]>(cloneColumns);

  const allColumnsKey = props.columns.map((col) => col.key);
  const aliveColumns = ref(aliveCache || allColumnsKey);
  const tableSettingOrigin: TableSetting = {
    isStriped: true,
    size: "medium",
    selection: true,
  };
  const tableSetting = ref<TableSetting>(settingCache || tableSettingOrigin);

  const cacheSetting = debounce(() => {
    if (!props.cacheKey) return;
    const columnsInfo: ColumnCache[] = [];
    for (const column of tableColumns.value) {
      columnsInfo.push({
        key: column.key,
        align: column.align || "left",
        fixed: column.fixed || false,
      });
    }
    console.log("table配置被缓存 —— ", props.cacheKey);

    localStg.set(cacheKey.setting, tableSetting.value);
    localStg.set(cacheKey.column, columnsInfo);
    localStg.set(cacheKey.alive, aliveColumns.value);
  }, 500);

  const resetSetting = () => {
    console.log("table配置缓存被删除 —— ", props.cacheKey);
    tableColumns.value = cloneDeep(props.columns);
    aliveColumns.value = allColumnsKey;
    localStg.remove(cacheKey.column);
    localStg.remove(cacheKey.alive);
  };

  if (columnsCache) {
    try {
      tableColumns.value = columnsCache.map((col) => {
        const columnVal = cloneColumns.find((colc) => colc.key === col.key);
        columnVal!.align = col.align;
        columnVal!.fixed = col.fixed as "left" | "right";
        return columnVal as DataTableColumn;
      });
    } catch (error) {
      console.error(error);
      resetSetting();
    }
  }

  watch(
    () => [tableColumns.value, tableSetting.value, aliveColumns.value],
    () => cacheSetting(),
    { deep: true }
  );

  return {
    columnsCache,
    settingCache,
    aliveCache,
    allColumnsKey,
    tableColumns,
    aliveColumns,
    tableSetting,
    resetSetting,
  };
};
